import React, { useEffect, useRef, useState } from 'react'
import './BillingDetails.less'
import { Alert, Button, Popconfirm, App, Descriptions, Spin, Space } from 'antd'
import { ProTable } from '@ant-design/pro-components'
import { useModel, useParams } from '@umijs/max'
import Notarization from '@/components/Notarization/Notarization'

const BillingDetails = () => {
  const tableRef = useRef()
  const routerParams = useParams()
  const { order_id } = routerParams

  const { BillPayment, GetBillDetail, IsOpenNotary } = useModel('BillingDetails')

  const { platformType, CheckOptionAuth } = useModel('Global')

  const { message, modal } = App.useApp()

  const [billList, setBillList] = useState([]) // 账单列表
  const [topInfo, setTopInfo] = useState({}) // 顶部信息
  const [userInfo, setUserInfo] = useState([]) // 用户信息

  const [loading, setLoading] = useState(true) // 加载状态

  const [notarizationAuth, setNotarizationAuth] = useState(false) // 公证权限

  useEffect(() => {
    GetBillList({ order_id })
    getNotarizationAuth()
  }, [order_id])

  // 公证权限查询
  const getNotarizationAuth = async () => {
    const res = await IsOpenNotary()
    res && setNotarizationAuth(res)
  }

  // 获取账单信息
  const GetBillList = async params => {
    setLoading(true)
    const res = await GetBillDetail(params)
    if (res) {
      setBillList(res.bill_list)
      setTopInfo(res.top_info)

      setUserInfo([
        {
          key: 'name',
          label: '姓名',
          children: res.user_info.name || '-'
        },
        {
          key: 'id_card',
          label: '身份证号',
          children: res.user_info.id_card || '-'
        },
        {
          key: 'mobile',
          label: '手机号',
          children: res.user_info.mobile || '-'
        }
      ])

      setLoading(false)
    }
  }

  // 支付方法
  const handleConfirmPayment = async (row, type) => {
    if (platformType === 0) return

    let params = {
      order_id: row.order_id,
      bill_num: row.bill_num,
      type // 1:确认支付 2:手动扣款 3:线下买断
    }
    const res = await BillPayment(params)
    if (res) {
      let typeText
      if (type === 1) typeText = '确认支付'
      if (type === 2) typeText = '手动扣款'
      if (type === 3) typeText = '线下买断'

      message.success(typeText + '成功')
      // tableRef.current.reload()
      GetBillList({ order_id })
    }
  }

  const baseColumns = [
    {
      title: '期数',
      dataIndex: 'bill_num',
      align: 'center'
    },
    {
      title: '租金',
      dataIndex: 'pay_money',
      align: 'center',
      render: text => {
        return <span>¥{text}</span>
      }
    },
    {
      title: '账单状态',
      dataIndex: 'is_pay',
      align: 'center',
      valueEnum: {
        1: { text: <span style={{ color: '#D92F26', fontWeight: 'bold' }}>未支付</span>, status: 'Error' },
        2: { text: <span style={{ color: '#00B42A', fontWeight: 'bold' }}>已支付</span>, status: 'Success' },
        3: { text: <span style={{ color: '#FAAD13', fontWeight: 'bold' }}>部分支付</span>, status: 'Warning' },
        4: { text: <span style={{ color: '#FAAD13', fontWeight: 'bold' }}>已续租</span>, status: 'Success' }
      }
    },
    {
      title: '到期日',
      dataIndex: 'dead_time',
      align: 'center',
      render: (text, record) => {
        console.log('record========', record)

        return (
          <>
            {record.overdueDay === 0 ? (
              <span>{text}</span>
            ) : (
              <span style={{ color: '#FE3850' }}>
                {text} (逾期 {record.overdueDay} 天)
              </span>
            )}
          </>
        )
      }
    },
    {
      title: '操作人',
      dataIndex: 'operator_name',
      align: 'center',
      render: (text, record) => {
        return <span>{record.is_pay === 2 && text === '-' ? <span>系统</span> : <span>{text}</span>}</span>
      }
    },
    {
      title: '支付时间',
      dataIndex: 'rec_time',
      align: 'center'
    },
    {
      title: '操作',
      key: 'option',
      width: 200,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        return (
          <>
            {!row.is_buyout ? (
              <>
                {CheckOptionAuth('confirm_bill') && (
                  <Popconfirm
                    key='confirm_payment'
                    title='确认后将关闭本期账单，是否确定该用户已经支付本期账单'
                    onConfirm={() => handleConfirmPayment(row, 1)}
                    okText='确认'
                    cancelText='取消'
                    disabled={row.is_pay === 2}
                  >
                    <Button
                      size='small'
                      className={row.is_pay === 2 ? 'btn_disabled' : null}
                      style={{ background: '#00B42A' }}
                      type='primary'
                    >
                      确认支付
                    </Button>
                  </Popconfirm>
                )}
                <Popconfirm
                  key='manual_deduction'
                  title='手动扣款将自动执行一次扣款，（失败后可再次发起）是否确定执行'
                  onConfirm={() => handleConfirmPayment(row, 2)}
                  okText='确认'
                  cancelText='取消'
                  disabled={row.is_pay === 2 || row.pay_type === 2}
                >
                  <Button
                    type='primary'
                    size='small'
                    className={row.is_pay === 2 || row.pay_type === 2 ? 'btn_disabled' : null}
                    style={{ marginLeft: '10px' }}
                  >
                    手动扣款
                  </Button>
                </Popconfirm>
              </>
            ) : null}

            {row.is_buyout === 1 ? (
              <Popconfirm
                key='buyout'
                title='是否确定该用户已经支付该笔买断款'
                onConfirm={() => handleConfirmPayment(row, 3)}
                okText='确认'
                cancelText='取消'
                disabled={row.is_pay === 2}
              >
                <Button
                  type='primary'
                  style={{ background: '#00B42A', width: '85%' }}
                  size='small'
                  className={row.is_pay === 2 ? 'btn_disabled' : null}
                >
                  线下买断
                </Button>
              </Popconfirm>
            ) : null}
          </>
        )
      }
    }
  ]

  const [columns, setColumns] = useState([])

  useEffect(() => {
    if (platformType === 1) {
      setColumns(baseColumns)
    } else {
      let tempArr = baseColumns.filter(item => item.title !== '操作')
      setColumns(tempArr)
    }
  }, [])

  return (
    <div className='billing_details'>
      {!loading ? (
        <Space direction='vertical' style={{ width: '100%' }} size={[20, 20]}>
          <Alert
            className={'alert_money_box'}
            message={
              <div className='alert_money'>
                <div>
                  总账单 : <span>{topInfo.total_bill_amount}元</span>
                </div>
                <div>
                  已收总和 : <span>{topInfo.received_bill_amount}元</span>
                </div>
                <div>
                  剩余待收 : <span>{topInfo.surplus_unpaid_bill_amount}元</span>
                </div>
                <div>
                  当前买断款 : <span>{topInfo.latestBuyOutMoney}元</span>
                </div>
              </div>
            }
            type='info'
            showIcon
            banner
          />

          <div>
            {notarizationAuth && platformType === 1 && order_id ? (
              <Space direction='vertical' style={{ width: '100%' }} size={[20, 20]}>
                <div className='billing_title'>账单详情</div>
                <Notarization order_id={order_id} />
              </Space>
            ) : null}
          </div>

          <Descriptions title='用户信息' bordered items={userInfo} />

          <>
            <div className='billing_title'>账单详情</div>
            <ProTable
              actionRef={tableRef}
              request={async params => {
                return {
                  data: billList,
                  success: true
                }
              }}
              toolBarRender={false}
              rowKey='id'
              scroll={{ x: 'max-content' }}
              columns={columns}
              pagination={false}
              search={false}
            />
          </>
        </Space>
      ) : (
        <div className='billing_loading'>
          <Spin />
        </div>
      )}
    </div>
  )
}
export default BillingDetails
